`use strict`;
const Controller = require('egg').Controller;
const fs = require("fs");
const toArray = require("stream-to-array");
const { get } = require("lodash");

class HomeController extends Controller {
  async health() {
    const ua = this.ctx.headers['user-agent'];
    this.ctx.body = 'Your ua: ' + (ua || '<none>');
  }

  async test() {

    const {
      app,
      ctx,
    } = this;


    const arr = [];
    let { beginDate } = ctx.query;


    let { startDate, endDate } = app.getMicDateDuration(beginDate);
    arr.push({ startDate, endDate });
    for (let i = 0; i < 96; i++) {  // 一天量
      if (i != 0) {
        let dealDate = app.getMicDateDuration(startDate);
        startDate = dealDate.startDate;
        endDate = dealDate.endDate;
        arr.push(dealDate);
      }

    }
    this.ctx.body = arr;
    // this.ctx.body = this.app.getMicDateDuration(1589207706);
  }


  async test2() {

    const { app, ctx } = this;

    const rules = {
      beginDate: 'required',
    };

    const messages = {
      'beginDate.required': '开始时间为必填项',
    };

    const errors = await app.validator.validate(ctx.query, rules, messages);
    // return ctx.body = JSON.stringify(errors);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { beginDate } = ctx.query;


    let { startDate, endDate } = app.getMicDateDuration(beginDate);
    const t_session = ctx.t_session;

    let params = {
      'start': startDate * 1000,
      'end': endDate * 1000,
      'current_page': '1',
      'page_size': '50',
      'session': t_session
    };
    const orderSelect = this.app.config.api.getOrders; // 获取请求url对象信息

    let res = await ctx.helper.http(orderSelect, params);
    let dealRes = res.service_task_packet.service_list;
    ctx.body = res; return;
    // ctx.service.checkInRecord.totalDealData(dealRes);
  }

  async getPull() {
    const { app, ctx } = this;

    const rules = {
      beginDate: 'required',
      type: 'required'
    };

    const messages = {
      'beginDate.required': '开始时间为必填项',
      'type': "查询类型为必填项"
    };

    const errors = await app.validator.validate(ctx.query, rules, messages);
    // return ctx.body = JSON.stringify(errors);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { beginDate,type } = ctx.query;

    let { startDate, endDate } = app.getMicDateDuration(beginDate);
    const t_session = ctx.t_session;
    let retArray = []; // 结果数组
    let num = parseInt(type) * 4;

    for (let i = 0; i < num; i++) {  // 一天量
      if (i != 0) {
        let dealDate = app.getMicDateDuration(startDate);
        startDate = dealDate.startDate;
        endDate = dealDate.endDate;
      }
      // let params = {
      //   'start': startDate * 1000,
      //   'end': endDate * 1000,
      //   'current_page': '1',
      //   'page_size': '50',
      //   'session': t_session
      // };
      // const orderSelect = this.app.config.api.getOrders; // 获取请求url对象信息

      // let res = await ctx.helper.http(orderSelect, params);
      const res = await ctx.service.checkInRecord.getScope(startDate * 1000, endDate * 1000,t_session);
      let dealRes = res.service_task_packet.service_list;
      if(!this.app.lodash.isEmpty(dealRes.service_task_d_o)) {
        this.app.lodash.forEach(dealRes.service_task_d_o,obj => {
          let arr = ['clothing_accessories_maintain', 'luggage_leather_maintain', 'shoe_maintain', 'clothing_cleaning','clothes_alter'];
          let isHas = arr.indexOf(obj.service_name);
          if(isHas !== -1){
            retArray.push(obj);
          }
          
        });
      }

      // ctx.service.checkInRecord.totalDealData(dealRes);
    }
    ctx.body = retArray;
  }


  async tnode() {
    const {
      ctx, app
    } = this;
    const appInfo = app.config.tinfor;

    const orderSelect = this.app.config.api.getOrders;

    app.logger.info("服务信息：%s", appInfo.secrect);
    const params = {
      'start': '1587273408',
      'end': '1587274248',
      'current_page': '1',
      'page_size': '50',
      'session': appInfo.session
    };

    let res = await ctx.helper.http(orderSelect, params);
    // 方式返回空对象

    this.ctx.body = this.app.lodash.isEmpty(res.service_task_packet.service_list) ? [] : res.service_task_packet.service_list;
  }

  /**
   * 获取工单
   */
  async getWorkOrders() {
    // const { cityId } = ctx.params;  get
    // const { idCard } = ctx.request.body;  post
    const {
      app,
      ctx,
    } = this;

    const rules = {
      startDate: 'required',
      endDate: 'required',
    };

    const messages = {
      'startDate.required': '开始时间为必填项',
      'endDate.required': '接受时间为必填项',
    };

    const errors = await app.validator.validate(ctx.query, rules, messages);
    // return ctx.body = JSON.stringify(errors);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { startDate, endDate } = ctx.query;
    const t_session = ctx.t_session;

    // const params = {
    //   'start': startDate,
    //   'end': endDate,
    //   'current_page': '1',
    //   'page_size': '50',
    //   'session': t_session
    // };
    // const orderSelect = this.app.config.api.getOrders; // 获取请求url对象信息

    const res = await ctx.service.checkInRecord.getScope(startDate, endDate,t_session);


    // 方式返回空对象
    ctx.body = this.app.lodash.isEmpty(res.service_task_packet.service_list) ? [] : res.service_task_packet.service_list;
  }

  /**
   * 获取分页
   */
  async getWorkOrderPages() {
    // const { cityId } = ctx.params;  get
    // const { idCard } = ctx.request.body;  post
    const {
      app,
      ctx,
    } = this;

    const rules = {
      page: 'required',
    };

    const messages = {
      'page.required': '页码必传'
    };

    const errors = await app.validator.validate(ctx.query, rules, messages);
    // return ctx.body = JSON.stringify(errors);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { page ,workcardId ,mobile,state } = ctx.query;
    const params = {};
    if(workcardId !== undefined && workcardId !=="") {
      Object.assign(params,{
        'workcardId': workcardId,
      });
    }
    if(mobile !== undefined && mobile !=="") {
      Object.assign(params,{
        'mobile': mobile,
      });
    }
    if(state !== undefined && state !=="") {
      Object.assign(params,{
        'state': state,
      });
    }


    const ret = await ctx.service.checkInRecord.getPagination(page, 10,params);
    // 方式返回空对象
    ctx.body = ret;
  }

  /**
   * 获取工单
   */
  async getWorkOrderById() {
    const state = 0; //获取工单
    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
    };


    const errors = await app.validator.validate(ctx.params, rules, messages);
    // return ctx.body = JSON.stringify(errors);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId } = ctx.params;

    const t_session = ctx.t_session;

    const params = {
      'parent_biz_order_id': workcardId,
      'session': t_session
    };
    const orderSelect = this.app.config.api.getOrderById;

    // let res = await ctx.helper.http(orderSelect, params);
    const res = await ctx.service.checkInRecord.getDetail(workcardId,t_session);

    let ok = this.app.lodash.isEmpty(res.service_task_packet.service_list.service_task_d_o);
    let content = res.service_task_packet.service_list.service_task_d_o;
    if (!ok) {
      this.app.logger.info("返回结果：%s",JSON.stringify(content[0]));
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, content);
    }
    // 方式返回空对象
    ctx.body = ok ? [] : content;
  }


  /**
   * 接单
   */
  async receiveOrder() {
    const state = 1; //接工单
    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      id:"required",
      content:"required"
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'id.required': 'id为必填项',
      'content.required': 'content为必填项'
    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    let { workcardId,id,content} = ctx.request.body;
    const t_session = ctx.t_session;

    try{ // json 是否序列化都可以哦。
      content = JSON.parse(content);
    }catch (e){
      content = content;
    }

    const params = {
      'workcard_id': id,
      'session': t_session
    };
    const receiveOrder = this.app.config.api.receiveOrder;
    Object.assign(params, receiveOrder.param);

    let res = await ctx.helper.http(receiveOrder, params);

    let result = get(res, 'result.success', false)
    if (result) { // 接单时候要入库哦
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, content,0);
      ctx.body = {
        status: true,
        msg: "接单成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "接单失败"
    };
  }

  /**
   * 物流取件
   */
  async expressPickUp() {
    const state = 2; // 物流取件
    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      expressCode: 'required',
      expressCompany: 'required',
      id:"required",
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'expressCode.required': '快递单号为必填项',
      'expressCompany.required': '快递公司为必填项',
      'id':'id为必填项'
    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId, expressCode, expressCompany,id } = ctx.request.body;
    const t_session = ctx.t_session;

    const params = {
      'express_code': expressCode,
      'express_company': expressCompany,
      'workcard_id': id,
      'session': t_session
    };
    const expressPickUp = this.app.config.api.expressPickUp;
    Object.assign(params, expressPickUp.param);

    let res = await ctx.helper.http(expressPickUp, params);
    let result = get(res, 'result.success', false)

    if (result) {
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, {fetch_express_num:expressCode,fetch_express_name:expressCompany});
      ctx.body = {
        status: true,
        msg: "成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "失败"
    };
  }

  /**
   * 服务商收货 3
   */
  async serviceBusinessReceive() {
    const state = 3; // 服务商收货

    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      id: 'required',
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'id.required': 'id为必填项',
    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId ,id} = ctx.request.body;
    const t_session = ctx.t_session;

    const params = {
      'workcard_id': id,
      'session': t_session
    };

    const expressPickUp = this.app.config.api.serviceBusinessReceive;
    Object.assign(params, expressPickUp.param); // 附加动作

    let res = await ctx.helper.http(expressPickUp, params);
    let result = get(res, 'result.success', false)

    if (result) {
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, {});
      ctx.body = {
        status: true,
        msg: "成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "失败"
    };
  }

  /**
   * 服务商更新厂内节点 4
   */
  async updateNode() {
    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      action: 'required',
      picUrlList: 'required',
      state: 'required',
      id: 'required',
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'action.required': '业务节点为必填项',
      'picUrlList.required': '图片自定义连接为必填项',
      'state.required': "状态必传",
      'id.required':"id为必填项"
    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }
    // 厂内节点自定义
    const { workcardId, action, picUrlList, state,id } = ctx.request.body;
    const t_session = ctx.t_session;

    const params = {
      'action': action,
      'pic_url_list': picUrlList,
      'workcard_id': id,
      'session': t_session
    };
    const updateNode = this.app.config.api.serviceBusinessUpdateNode;

    let res = await ctx.helper.http(updateNode, params);
    let result = get(res, 'result.success', false)

    if (result) {
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, {});
      ctx.body = {
        status: true,
        msg: "成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "失败"
    };
  }

  /**
  * 服务商服务完成，等待寄出  5
  */
  async waitSend() {
    const state = 5; // 服务商服务完成，等待寄出

    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      id:'required'
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'id.required': 'id为必填项',

    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId ,id} = ctx.request.body;
    const t_session = ctx.t_session;

    const params = {
      'workcard_id': id,
      'session': t_session
    };
    const waitSend = this.app.config.api.serviceBusinessWaitSend;
    Object.assign(params, waitSend.param); // 附加动作

    let res = await ctx.helper.http(waitSend, params);
    let result = get(res, 'result.success', false)

    if (result) {
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, {});
      ctx.body = {
        status: true,
        msg: "成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "失败"
    };
  }

  /**
  * 服务商服务完成，已经寄出 6
  */
  async serviceBusinessSendOff() {
    const state = 6; // 服务商服务完成，已经寄出
    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      expressCode: 'required',
      expressCompany: 'required',
      id: 'required',
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'expressCode.required': '快递单号为必填项',
      'expressCompany.required': '快递公司为必填项',
      'id.required': 'id为必填项',

    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId, expressCode, expressCompany,id } = ctx.request.body;
    const t_session = ctx.t_session;

    const params = {
      'express_code': expressCode,
      'express_company': expressCompany,
      'workcard_id': id,
      'session': t_session
    };
    const sendOff = this.app.config.api.serviceBusinessSendOf;
    Object.assign(params, sendOff.param);

    let res = await ctx.helper.http(sendOff, params);
    let result = get(res, 'result.success', false)

    if (result) {
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, {send_express_num:expressCode,send_express_name:expressCompany});
      ctx.body = {
        status: true,
        msg: "成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "失败"
    };
  }

  /**
   * 服务商服务完成，等待消费者核销  7
   */
  async confirm() {
    const state = 7; // 服务商服务完成，等待消费者核销

    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required',
      id: 'required',
    };

    const messages = {
      'workcardId.required': '工单号为必填项',
      'id.required': 'id必填项',

    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId,id } = ctx.request.body;
    const t_session = ctx.t_session;

    const params = {
      'workcard_id': id,
      'session': t_session
    };
    const confirm = this.app.config.api.confirm;


    let res = await ctx.helper.http(confirm, params);
    let result = get(res, 'result.success', false)

    if (result) {
      ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, {});
      ctx.body = {
        status: true,
        msg: "成功"
      };
      return;
    }
    ctx.body = {
      status: false,
      msg: "失败"
    };
    return;
  }


  /**
   * 图片上传
   */
  async upload() {
    const { app, ctx } = this;
    // 获取文件流
    // const stream = await this.ctx.getFileStream();

    const parts = ctx.multipart({
      autoFields: true,
    });
    const extraParams = parts.field;
    const stream = await parts();
    const streamToBuffer = stream => {
      return new Promise((resolve, reject) => {
        const buffers = [];
        stream.on('error', reject);
        stream.on('data', data => buffers.push(data));
        stream.on('end', () => resolve(Buffer.concat(buffers)));
      });
    };
    const t_session = ctx.t_session;
    const buf = await streamToBuffer(stream);
    // const parts = await toArray(stream);
    let data = new Buffer(buf, "'binary'")

    const params = {
      'img': data,
      'picture_name': '1.png',
      'is_https': false,
      'session': t_session
    };
    const confirm = this.app.config.api.upload;

    let res = await ctx.helper.http(confirm, params);
    // Object.assign(res,extraParams);
    ctx.body = res.result.success ? res.result.value : "";
  }


  /**
   * 更新状态
   */
  async updateState() {
    const {
      app,
      ctx,
    } = this;

    const rules = {
      workcardId: 'required'
    };

    const messages = {
      'workcardId.required': '工单号为必填项'
    };

    const errors = await app.validator.validate(ctx.request.body, rules, messages);
    if (errors) {
      ctx.set('Content-Type', 'application/json; charset=utf8');
      ctx.throw(422, '验证失败', {
        errors,
      });
    }

    const { workcardId,state,remark } = ctx.request.body;
    const t_session = ctx.t_session;
    let params = {};
    let type = 1;
    if(remark !== undefined && remark !=="") {
	  app.logger.info("服务信息：%s", remark);
      Object.assign(params,{
       remark
      });
      type = 3;
    }

    ctx.service.checkInRecord.dealByWorkCardId(workcardId, state, params,type);
    ctx.body = {
      status: true,
      msg: "成功"
    };
    return;
  }



}

module.exports = HomeController;